package com.cskaoyan.javase.oop3._2example.operation.impl;

import com.cskaoyan.javase.oop3._2example.model.Goods;
import com.cskaoyan.javase.oop3._2example.model.GoodsData;
import com.cskaoyan.javase.oop3._2example.operation.IGoods;

/**
 * 对库存做数据处理和业务操作
 * @since 15:41
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class IGoodsImpl implements IGoods {
    private Goods[] gs = GoodsData.GOODS;

    @Override
    public Goods[] getAllGoods() {
        // 去除gs中的null元素
        int count = 0;
        for (Goods g : gs) {
            if (g != null) {
                count++;
            }
        }
        Goods[] result = new Goods[count];
        int newIndex = 0;
        // 遍历赋值
        for (Goods g : gs) {
            if (g != null) {
                result[newIndex] = g;
                newIndex++;
            }
        }
        return result;
    }

    @Override
    public boolean createGoods(Goods g) {
        // 先校验id的唯一性
        for (Goods goods : getAllGoods()) {
            if (goods.getId() == g.getId()) {
                System.out.println("id重复了!");
                return false;
            }
        }
        // 将数组中的null元素赋值为对象
        for (int i = 0; i < gs.length; i++) {
            if (gs[i] == null) {
                gs[i] = g;
                return true;
            }
        }
        // 数组已经满了，返回false
        return false;
    }

    @Override
    public boolean deleteGoods(int id) {
        // 将数组中的对象元素赋值为null
        for (int i = 0; i < gs.length; i++) {
            // 排除null元素，避免空指针异常
            if (gs[i] == null) {
                continue;
            }
            if (gs[i].getId() == id) {
                // 找到了，删除
                gs[i] = null;
                return true;
            }
        }
        // 没找到目标id
        return false;
    }
}
